package com.example.demo.util;



import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

@Component
@RequiredArgsConstructor
public class HashUtils {
@Autowired
    private final ObjectMapper objectMapper;

    // 从配置文件读取密钥（增强安全性）
    @Value("${hash.secret-key}")
    private String secretKey;

    public  String convertMapToString(SortedMap<String, Object> fields) {
        try {
            return objectMapper.writeValueAsString(fields);
        } catch (JsonProcessingException e) {
            throw new RuntimeException("字段转换JSON失败", e);
        }
    }

    /**
     * 计算初始哈希（无前置哈希）
     */
    public String calculateInitialHash(Map<String, Object> coreFields) {
        try {
            // 使用TreeMap确保字段按key排序，避免顺序影响哈希
            TreeMap<String, Object> sortedFields = new TreeMap<>(coreFields);

            // 拼接密钥和字段（密钥增强安全性）
            String content = secretKey + "|" + objectMapper.writeValueAsString(sortedFields);

            // 计算SHA-256哈希
            MessageDigest digest = MessageDigest.getInstance("SHA-256");
            byte[] hashBytes = digest.digest(content.getBytes(StandardCharsets.UTF_8));

            // 转换为十六进制字符串
            return bytesToHex(hashBytes);
        } catch (NoSuchAlgorithmException | JsonProcessingException e) {
            throw new RuntimeException("哈希计算失败", e);
        }
    }

    /**
     * 计算链式哈希（基于上一版本的哈希）
     */
    public String calculateChainHash(String previousHash, Map<String, Object> currentFields) {
        try {
            TreeMap<String, Object> sortedFields = new TreeMap<>(currentFields);

            // 拼接密钥、上一版本哈希和当前字段（形成链条）
            String content = secretKey + "|" + previousHash + "|" +
                    objectMapper.writeValueAsString(sortedFields);

            MessageDigest digest = MessageDigest.getInstance("SHA-256");
            byte[] hashBytes = digest.digest(content.getBytes(StandardCharsets.UTF_8));

            return bytesToHex(hashBytes);
        } catch (NoSuchAlgorithmException | JsonProcessingException e) {
            throw new RuntimeException("哈希链计算失败", e);
        }
    }

    /**
     * 将JSON字符串解析为核心字段Map
     */
    public Map<String, Object> parseCoreFields(String json) {
        try {
            return objectMapper.readValue(json, new TypeReference<Map<String, Object>>() {});
        } catch (JsonProcessingException e) {
            throw new RuntimeException("解析核心字段失败", e);
        }
    }

    /**
     * 字节数组转十六进制字符串
     */
    private String bytesToHex(byte[] hash) {
        StringBuilder hexString = new StringBuilder(2 * hash.length);
        for (byte b : hash) {
            String hex = Integer.toHexString(0xff & b);
            if (hex.length() == 1) {
                hexString.append('0');
            }
            hexString.append(hex);
        }
        return hexString.toString();
    }
}
